<template>
	<view class="container">
		<!-- 公司信息表单 -->
		<view class="form-section">
			<!-- 公司名称 -->
			<view class="form-item">
				<text class="label">公司名称</text>
				<input class="input" v-model="form.companyName" placeholder="请输入公司名称" />
			</view>

			<!-- 联系人 -->
			<view class="form-item">
				<text class="label">联系人</text>
				<input class="input" v-model="form.contact" placeholder="请输入联系人" />
			</view>

			<!-- 联系电话 -->
			<view class="form-item">
				<text class="label">联系电话</text>
				<view class="phone-input">
					<text class="country-code">+86</text>
					<input class="input" v-model="form.phone" placeholder="请输入联系电话" type="number" />
				</view>
			</view>

			<!-- 省市区选择 -->
			<view class="form-item address-item">
				<text class="label">所在地区</text>
				<view class="location-select">
					<!-- 省份选择 -->
					<picker mode="selector" :range="provinces" @change="onProvinceChange" :value="provinceIndex">
						<view class="picker-view">
							<text>{{ provinces[provinceIndex] || '请选择省份' }}</text>
							<text class="arrow">▼</text>
						</view>
					</picker>

					<!-- 城市选择 -->
					<picker mode="selector" :range="cities" @change="onCityChange" :value="cityIndex">
						<view class="picker-view">
							<text>{{ cities[cityIndex] || '请选择城市' }}</text>
							<text class="arrow">▼</text>
						</view>
					</picker>

					<!-- 区县选择 -->
					<picker mode="selector" :range="areas" @change="onAreaChange" :value="areaIndex">
						<view class="picker-view">
							<text>{{ areas[areaIndex] || '请选择区县' }}</text>
							<text class="arrow">▼</text>
						</view>
					</picker>
				</view>
			</view>

			<!-- 详细地址 -->
			<view class="form-item">
				<text class="label">详细地址</text>
				<input class="input" v-model="form.address" placeholder="请输入详细地址" />
			</view>

			<!-- 确认按钮 -->
			<button class="confirm-btn" @click="onConfirm">确认</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 表单数据
				form: {
					companyName: "",
					contact: "",
					phone: "",
					address: "",
					province: "",
					city: "",
					area: ""
				},
				info: {},

				// 省市区原始数据
				addressData: [],
				cityData: [],
				areaData: [],

				// 选择器数据
				provinces: [],
				cities: [],
				areas: [],

				// 选择索引
				provinceIndex: 0,
				cityIndex: 0,
				areaIndex: 0
			};
		},
		onLoad(val) {
			this.info = JSON.parse(val.qr || '{}')
			console.log(this.info);
			this.getAddressList()
		},
		methods: {
			getAddressList() {
				uni.request({
					url: 'https://apis.map.qq.com/ws/district/v1/list?key=LZKBZ-BYEK5-43OIM-IBRO4-TU7RV-3YFNJ',
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data.status === 0) {
							// 保存原始数据（省、市、区三级数据）
							this.addressData = res.data.result[0] || []; // 省份数据
							this.cityData = res.data.result[1] || []; // 城市数据
							this.areaData = res.data.result[2] || []; // 区县数据

							// 初始化省份列表
							this.provinces = this.addressData.map(item => item.name);

							// 默认选中浙江省
							this.provinceIndex = this.provinces.indexOf("浙江省") || 0;
							this.updateCities();
							console.log(this.addressData);
							console.log(this.cityData);
							console.log(this.areaData);
						} else {
							console.error('调用接口失败，使用默认地址数据', res.data);
							this.initDefaultData();
						}
					},
					fail: (err) => {
						console.error('请求接口失败，使用默认地址数据', err);
						this.initDefaultData();
					}
				});
			},

			// 初始化默认数据（接口失败时使用）
			initDefaultData() {
				// 简单的默认省市区数据
				this.addressData = [{
					id: '330000',
					name: '浙江省'
				}];
				this.cityData = [{
					id: '330200',
					name: '宁波市'
				}];
				this.areaData = [{
					id: '330201',
					name: '市辖区'
				}];

				this.provinces = this.addressData.map(item => item.name);
				this.provinceIndex = this.provinces.indexOf("浙江省") || 0;
				this.updateCities();
			},

			// 省份选择改变
			onProvinceChange(e) {
				this.provinceIndex = e.detail.value;
				this.form.province = this.provinces[this.provinceIndex] || '';
				// 重置城市和区县选择
				this.cityIndex = 0;
				this.areaIndex = 0;
				this.cities = [];
				this.areas = [];
				// 更新城市列表
				this.updateCities();
			},

			// 城市选择改变
			onCityChange(e) {
				this.cityIndex = e.detail.value;
				this.form.city = this.cities[this.cityIndex] || '';
				// 重置区县选择
				this.areaIndex = 0;
				this.areas = [];
				// 更新区县列表
				this.updateAreas();
			},

			// 区县选择改变
			onAreaChange(e) {
				this.areaIndex = e.detail.value;
				this.form.area = this.areas[this.areaIndex] || '';
			},

			// 更新城市列表（通过id前两位匹配省份）
			updateCities() {
				const selectedProvince = this.addressData[this.provinceIndex];
				if (!selectedProvince) {
					this.cities = [];
					this.areas = [];
					this.form.city = "";
					this.form.area = "";
					return;
				}

				// 获取省份id的前两位作为匹配依据
				const provinceIdPrefix = selectedProvince.id.substring(0, 2);

				// 筛选出id前两位与省份相同的城市
				const matchedCities = this.cityData.filter(city =>
					city.id.substring(0, 2) === provinceIdPrefix
				);

				this.cities = matchedCities.map(item => item.name);
				this.form.city = this.cities[0] || "";
				this.updateAreas();
			},

			// 更新区县列表（通过id前四位匹配城市）
			updateAreas() {
				const selectedProvince = this.addressData[this.provinceIndex];
				if (!selectedProvince || !this.cities.length) {
					this.areas = [];
					this.form.area = "";
					return;
				}

				// 获取省份id前两位
				const provinceIdPrefix = selectedProvince.id.substring(0, 2);
				// 找到当前选中的城市对象
				const matchedCities = this.cityData.filter(city =>
					city.id.substring(0, 2) === provinceIdPrefix
				);
				const selectedCity = matchedCities[this.cityIndex];

				if (selectedCity) {
					// 获取城市id的前四位作为匹配依据
					const cityIdPrefix = selectedCity.id.substring(0, 4);
					// 筛选出id前四位与城市相同的区县
					const matchedAreas = this.areaData.filter(area =>
						area.id.substring(0, 4) === cityIdPrefix
					);
					this.areas = matchedAreas.map(item => item.fullname);
					this.form.area = this.areas[0] || "";
				} else {
					this.areas = [];
					this.form.area = "";
				}
			},

			// 确认提交
			onConfirm() {
				// 完善校验
				if (
					!this.form.companyName ||
					!this.form.contact ||
					!this.form.phone ||
					!this.form.province ||
					!this.form.city ||
					!this.form.address
				) {
					uni.showToast({
						title: "请填写完整信息",
						icon: "none",
					});
					return;
				}

				// 提交表单
				const fullAddress = `${this.form.province}${this.form.city}${this.form.area}${this.form.address}`;
				console.log("完整地址：", fullAddress);
				console.log("表单数据：", this.form);
				var body = {
					customId: '',
					openId: wx.getStorageSync('openid'),
					activityItemId: this.info.SystemSoftwareId,
					customName: this.form.companyName,
					contacts: this.form.contact,
					tel: this.form.phone,
					dataStatus: '1',
					province: this.form.province,
					city: this.form.city,
					area: this.form.area,
					country: '',
					address: this.form.address,
				}
				uni.request({
					url: 'https://tangyun.tangyuntech.com/CustomManageApi/SaveCustomData', // 后端接口地址，需替换为实际地址
					method: 'POST',
					data: body,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.showToast({
								title: "提交成功",
								icon: "success",
							});
							setTimeout(_=>{
								uni.reLaunch({
									url:'/pages/home/index1'
								})
							},500)
							
						} else {
							console.error('调用失败', res.errors);
							uni.showToast({
								title: "调用失败",
								icon: "error",
							});
						}
					},
					fail: (err) => {
						console.error('请求后端接口失败', err);
					}
				});

				// 提交成功提示
				
			},
		},
	};
</script>

<style scoped>
	.container {
		padding: 16px;
		background-color: #fff;
	}

	.form-section {
		background-color: #fff;
	}

	.form-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 16px;
	}

	.label {
		font-size: 14px;
		color: #333;
		margin-bottom: 4px;
		font-weight: bold;
	}

	.input {
		padding: 10px;
		border: 1px solid #eee;
		border-radius: 4px;
		font-size: 14px;
		color: #666;
	}

	.phone-input {
		display: flex;
		align-items: center;
	}

	.country-code {
		padding: 10px;
		border: 1px solid #eee;
		border-right: none;
		border-radius: 4px 0 0 4px;
		background-color: #f8f8f8;
		color: #333;
	}

	.address-item {
		margin-bottom: 20px;
	}

	.location-select {
		display: flex;
		gap: 6px;
		width: 100%;
	}

	.picker-view {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 8px;
		border: 1px solid #eee;
		border-radius: 4px;
		background-color: #f8f8f8;
		color: #333;
		font-size: 14px;
		min-height: 44px;
		box-sizing: border-box;
	}

	.arrow {
		font-size: 12px;
		color: #999;
	}

	.confirm-btn {
		width: 100%;
		background-color: #f00;
		color: #fff;
		font-size: 16px;
		padding: 5px 12px;
		border-radius: 4px;
		margin-top: 24px;
	}
</style>